package cc.magicjson.config;

import cc.magicjson.factory.YamlPropertySourceFactory;
import cc.magicjson.plugin.ColumnNameConversionInterceptor;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
//@ConfigurationProperties(prefix = "spring.datasource.mybatis")
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
@EnableTransactionManagement
@MapperScan(basePackages = "cc.magicjson.mybatis.mapper", sqlSessionFactoryRef = "mybatisSqlSessionFactory")
public class MyBatisDataSourceConfig {
    @Value("${spring.datasource.mybatis.url}")
    private String url;

    @Value("${spring.datasource.mybatis.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.mybatis.username}")
    private String username;

    @Value("${spring.datasource.mybatis.password}")
    private String password;

    @Bean(name = "mybatisDataSource")
    public DataSource mybatisDataSource() {
        return DataSourceBuilder.create()
            .type(HikariDataSource.class)
            .url(url)
            .driverClassName(driverClassName)
            .username(username)
            .password(password)
            .build();
    }

    @Bean(name = "mybatisSqlSessionFactory")
    public SqlSessionFactory mybatisSqlSessionFactory(@Qualifier("mybatisDataSource") DataSource dataSource,
                                                  ColumnNameConversionInterceptor columnNameConversionInterceptor) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        if (columnNameConversionInterceptor.isEnabled()) {
            factoryBean.setPlugins(columnNameConversionInterceptor);
        }
        return factoryBean.getObject();
    }

    @Bean(name = "mybatisTransactionManager")
    public DataSourceTransactionManager mybatisTransactionManager(@Qualifier("mybatisDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
